package com.shell.customer.base.service.impl;

import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.persistence.service.impl.PersistentServiceImpl;
import com.shell.customer.base.dao.CusRelDao;
import com.shell.customer.base.service.CusRecService;
import com.shell.customer.base.service.CusRelService;
import com.shell.customer.group.service.CusGrpService;
import com.shell.customer.po.CusGrp;
import com.shell.customer.po.CusInvt;
import com.shell.customer.po.CusRec;
import com.shell.customer.po.CusRel;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service("pubCusRelService")
public class CusRelServiceImpl extends PersistentServiceImpl<CusRel> implements CusRelService {
	@Autowired
	CusRecService customerCService;
	@Autowired
	CusRelDao pubCusRelDao;
	@Autowired
	CusGrpService cusGrpService;

	public List<CusRel> setCusRel(CusInvt cusInvt, CusRec cus) {
		List<CusRel> saveRels = new ArrayList();
		CusRel cusRel = new CusRel();
		cusRel.setSrcId(cusInvt.getInviterId());
		cusRel.setTgtId(cusInvt.getInviteeId());
		CusGrp cusGrp = (CusGrp) this.cusGrpService.selectByKey(cusInvt.getInviterId());
		if (cusGrp == null) {
			cusRel.setRelType("1");
			saveRels.add(cusRel);
			save(cusRel);
		}
		return saveRels;
	}

	public List<CusRel> getCusRelFromMember(String supplierId) {
		return this.pubCusRelDao.getCusRelFromMember(supplierId);
	}

	public String selectSrcId(String tgtId, String relType) {
		Example example = new Example(CusRel.class);
		Example.Criteria criteria = example.createCriteria();
		if (StringUtil.notEmpty(relType)) {
			criteria.andEqualTo("relType", relType);
		}
		if (StringUtil.notEmpty(tgtId)) {
			criteria.andEqualTo("tgtId", tgtId);
		}
		List<CusRel> cusRels = selectByExample(example);
		if ((cusRels != null) && (cusRels.size() > 0)) {
			return ((CusRel) cusRels.get(0)).getSrcId();
		}
		return null;
	}

	public List<CusRel> selectBySrcAndType(String srcId, String relType) {
		CusRel rel = new CusRel();
		rel.setSrcId(srcId);
		rel.setRelType(relType);
		return selectByEntity(rel);
	}
}
